#! /usr/bin/perl
#
# Copyright 2014, General Dynamics C4 Systems
#
# SPDX-License-Identifier: GPL-2.0-only
#

$literate = 0;
$literate = 1 if $ARGV[0] eq "-l";

$prefix = $literate ? "> " : "";

# read the entire input
$/ = undef;
$input = <STDIN>;

# find the module name
$input =~ /module\s+([A-Z][a-zA-Z0-9._]*)/m or die "no module";
$modname = $1;

# find the lists of hs-boot imports and exports
$input =~ /{-# BOOT-IMPORTS:((\s+#?[A-Z][a-zA-Z0-9._]+(\(.*?\))?(%[a-zA-Z]+)?)*) #-}/
    or die "no imports";
$imports = $1;

$input =~ /{-# BOOT-EXPORTS:((\s+#?[a-zA-Z][a-zA-Z0-9_']+(\(.*?\))?)*) #-}/
    or die "no exports";
$exports = $1;

# transform the import list to import statements
$imports =~ s/\s+/\n${prefix}import /g;
$imports =~ s/#/{-# SOURCE #-} /g;
$imports =~ s/%/ as /g;

# create the export list
$explist = $exports;
$explist =~ s/\s#\w+//g;
$explist =~ s/(\w|\))\s/\1, /g;

# print the module & import statements
print "${prefix}-- this file is automatically generated, do not edit\n";
print "${prefix}module $modname($explist) where\n${prefix}import Prelude hiding(Word)\n$imports\n\n";

$exports =~ s/#//g;
$exports =~ s/\(.*?\)//g;

# find and print all the type definitions...
while($exports =~ / ([A-Z][a-zA-Z0-9']*)/g) {
    $name = $1;

    if (not $literate and
        $input =~ /^((type|newtype|data|class)\s+([A-Z][a-zA-Z0-9_' ]*=>\s+)?$name\W.*?)^\S/ms)
    {
        print "$1";
    } elsif ($literate and
        $input =~ /^(> (type|newtype|data|class)\s+([A-Z][a-zA-Z0-9_' ]*=>\s+)?$name\W.*?)^> \S/ms)
    {
        print "$1";
    }
}

# ...and the type signatures
while($exports =~ / ([a-z][a-zA-Z0-9']*)/g) {
    $name = $1;

    if (not $literate and $input =~ /^($name\s+::.*?)^\S/ms) {
        print "$1";
    } elsif ($literate and $input =~ /^(> $name\s+::.*?)^> \S/ms) {
        print "$1";
    }
}

